<template>
  <!-- 编辑报警设备弹窗 -->
  <a-modal
    v-model:open="visible"
    :title="'编辑'"
    :centered="true"
    :ok-text="'保存'"
    :confirm-loading="confirmLoading"
    width="562px"
    @ok="formOk"
    @cancel="cancel"
  >
    <a-spin :spinning="modalLoading">
      <a-form
        ref="formRef"
        layout="vertical"
        class="form"
        :model="formState"
        :rules="formRules"
      >
        <a-form-item name="ip" label="IP">
          <a-input v-model:value.trim="formState.ip" disabled></a-input>
        </a-form-item>
        <a-form-item name="name" label="报警器名称">
          <a-input
            v-model:value.trim="formState.name"
            :maxlength="10"
            placeholder="请输入报警器名称"
          ></a-input>
        </a-form-item>
        <a-form-item name="locationId" label="所属场景">
          <a-tree-select
            v-model:value="formState.locationId"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            allow-clear
            tree-default-expand-all
            :field-names="{ children: 'children', label: 'name', value: 'id' }"
            :tree-data="treeData"
            placeholder="请选择所属场景"
            :get-popup-container="(e: any) => e.parentNode"
            tree-node-filter-prop="label"
          ></a-tree-select>
        </a-form-item>
        <!-- :field-names="{ label: 'label', value: 'id', children: 'children' }" -->
        <a-form-item name="deviceIds" label="绑定摄像头">
          <a-cascader
            :value="formState.deviceIds"
            multiple
            :get-popup-container="(e: any) => e.parentNode"
            :options="deviceOptions"
            max-tag-count="responsive"
            :field-names="{
              label: 'name',
              value: 'areaOrDeviceId',
              children: 'children',
            }"
            expand-trigger="hover"
            :style="{ height: 'auto !important' }"
            placeholder="请选择摄像头"
            allow-clear
            :show-checked-strategy="'SHOW_CHILD'"
            show-search
            @change="changeDeviceList"
          ></a-cascader>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
const emits = defineEmits<{
  (e: "load-data"): void;
}>();
const treeData = ref();
import { DataRefluxApi, AlarmDeviceManagementAPI } from "../../api";
import { g6DeepClone } from "glasssix-utils-ts";
const $message: any = inject("$message");
const modalLoading = ref(false);
const visible = ref(false);
const formRef = ref();
const detailDeviceIds = ref([]);
const deviceInfoList = ref(
  [] as Array<{
    id: any;
    areaOrDeviceId: any;
    configId: null;
    label: any;
    deviceId: any;
  }>
);
const deviceOptions = ref([]);

const formState = ref({
  id: "",
  ip: "",
  name: "",
  locationId: undefined,
  deviceIds: [],
});
const formRules: Record<string, any> = {
  name: [{ required: true, message: "请输入报警器名称", trigger: "change" }],
  deviceIds: [{ required: true, message: "请选择摄像头", trigger: "change" }],
  locationId: [
    { required: true, message: "请选择所属场景", trigger: "change" },
  ],
};
const cancel = () => {
  formState.value = {
    id: "",
    ip: "",
    name: "",
    locationId: undefined,
    deviceIds: [],
  };
  detailDeviceIds.value = [];
  visible.value = false;
};
const confirmLoading = ref(false);
const formOk = () => {
  formRef.value
    .validate()
    .then(async (result: any) => {
      let params = g6DeepClone(formState.value);
      delete params.deviceIds;
      params.boxDeviceIds = deviceInfoList.value.map(
        (item) => item.areaOrDeviceId
      );
      confirmLoading.value = true;
      let res = await AlarmDeviceManagementAPI.updateInfo(params);
      confirmLoading.value = false;
      console.log("更新成功", result, res);
      if (res.code === 0) {
        emits("load-data");
        $message.success("操作成功");
        visible.value = false;
        cancel();
      }
    })
    .catch(() => {
      console.log("验证失败");
    });
};

// 摄像头

// 递归筛选
const findObjectById = (data: any, areaOrDeviceId: string): any => {
  for (let i = 0; i < data.length; i++) {
    const obj = data[i];
    if (obj.areaOrDeviceId === areaOrDeviceId) {
      return obj;
    }

    if (obj.children && obj.children.length > 0) {
      const result = findObjectById(obj.children, areaOrDeviceId);
      if (result) {
        return result;
      }
    }
  }
  return null;
};
const changeDeviceList = (value: any): void => {
  console.log("选择摄像头", value);

  deviceInfoList.value = [];
  value.forEach((item: any) => {
    const re = findObjectById(deviceOptions.value, item[item.length - 1]);
    console.log(re);

    // 选中盒子时将所有子项的deviceId获取到
    if (re?.children) {
      re.children.forEach((itemChild: any) => {
        if (itemChild.disabled === 0) {
          let itemInfo = {
            id: itemChild.id,
            deviceId: itemChild.deviceId,
            areaOrDeviceId: itemChild.areaOrDeviceId,
            configId: null,
            label: itemChild.label,
            disabled: itemChild.disabled,
          };
          deviceInfoList.value.push(itemInfo);
        }
      });
    } else {
      // 选中子项时直接把deviceId获取到
      let itemInfo = {
        id: re.id,
        deviceId: re.deviceId,
        areaOrDeviceId: re.areaOrDeviceId,
        configId: null,
        label: re.label,
      };
      deviceInfoList.value.push(itemInfo);
    }
  });
  formState.value.deviceIds = value;
};

// 详情处理回显已选设备

const findParentIds = (areaOrDeviceId: string, data: any[]) => {
  const parentIds: any = [];

  const findParentRecursive = (node: any) => {
    if (node.areaOrDeviceId === areaOrDeviceId) {
      parentIds.unshift(node.areaOrDeviceId); // 将当前节点id添加到数组的开头
      return true;
    }

    if (node.children && node.children.length > 0) {
      for (const child of node.children) {
        if (findParentRecursive(child)) {
          parentIds.unshift(node.areaOrDeviceId); // 将当前节点id添加到数组的开头
          return true;
        }
      }
    }

    return false;
  };

  for (const tree of data) {
    findParentRecursive(tree);
  }

  return parentIds;
};

// 删除无效id
const delInvalidId = (treeData: any, deviceId: any): any => {
  const newList = [...new Set(deviceId.flat())];
  let deviceIds = deviceId;
  const getTreeById = (treeData: any, key: any): any => {
    for (let i = 0; i < treeData.length; i++) {
      if (treeData[i].areaOrDeviceId === key) {
        return false; // 找到了目标节点，返回节点信息
      }
      if (treeData[i].children && treeData[i].children.length > 0) {
        const result = getTreeById(treeData[i].children, key); // 递归查找
        if (!result) {
          return false; // 如果在子节点中找到了目标节点，返回结果
        }
      }
    }
    return key; // 遍历完当前节点和子节点都没有找到目标节点，返回null
  };

  // 删除不存在的id数组
  const delNotIdArry = (): any => {
    newList.forEach((key) => {
      if (getTreeById(treeData, key)) {
        let delKey = getTreeById(treeData, key);
        let del = deviceIds.findIndex(
          (item: any) => item[0] === delKey || item[1] === delKey
        );
        deviceIds.splice(del, 1);
      }
    });
    return deviceIds;
  };

  return delNotIdArry();
};

const detailDeviceOperation = () => {
  let deviceIds = detailDeviceIds.value;
  // 1、 去掉设备列表没有的id
  deviceIds = !deviceIds
    ? undefined
    : delInvalidId(deviceOptions.value, deviceIds);
  // 2、组装回显设备的数据格式 例如：[[1,1-1,1-1-2], [2,2-1,2-1-2]]
  deviceIds.forEach((item: any, index: number, arr: any[]) => {
    arr[index] = findParentIds(item, deviceOptions.value);
  });
  formState.value["deviceIds"] = deviceIds;
  // 3、回显选择后的设备
  changeDeviceList(formState.value["deviceIds"]);
};

const getVideoDeviceTree = async () => {
  // const res: TsRes = await AlarmNoticeAPI.boxDeviceList();
  const res: TsRes = await DataRefluxApi.getDeviceTree();
  if (res.code === 0) {
    console.log("响应", res.data);
    deviceOptions.value = res.data;
    detailDeviceOperation();
    deviceOptions.value = res.data;
  }
};

const open = async (treeList: any, itemInfo: any) => {
  modalLoading.value = true;
  visible.value = true;
  console.log("组织树", treeData, itemInfo);
  treeData.value = treeList;
  if (itemInfo.boxDevices) {
    detailDeviceIds.value = itemInfo.boxDevices.map(
      (item: any) => item.deviceId
    );
  }
  console.log("需要回显树的id", detailDeviceIds.value);
  await getVideoDeviceTree();
  console.log("需要回显树的id", detailDeviceIds.value);

  for (let key in formState.value) {
    if (Object.prototype.hasOwnProperty.call(itemInfo, key)) {
      // @ts-ignore
      formState.value[key] = itemInfo[key];
    }
  }
  modalLoading.value = false;
  console.log("end", formState.value);
};

defineExpose({ open });
</script>

<style lang="less" scoped>
.form {
  display: flex;
  padding: 40px;
  gap: 32px;
  flex-flow: column;
}
</style>
